'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 外部接口的过滤类
 * @author sundbcn@gmail.com (sun debing)
 */

var _ = require('lodash');
var crypto = require('crypto');
var configUtil = require('../../../util/configUtil.js');
var game_config = configUtil.load('game');

module.exports = function () {
    return new Filter();
};

var Filter = function () {

};

Filter.prototype.before = function (msg, session, next) {
    var verify = msg.query.verify;
    if (!verify) {
        return next(new Error('verify is empty'));
    }
    delete msg.query.verify;

    var check_info = _calcVerify(msg.query);
    if (check_info != verify) {
        return next(new Error('verify error require [' + check_info + '], get [' + verify + ']'));
    }

    next();
};

var _calcVerify = function (params) {
    var query_list = [];
    _.forEach(params, function (value, key) {
        query_list.push(key + '=' + value);
    });
    query_list = _.sortBy(query_list);
    var verify_string = game_config.mgr_key;
    _.each(query_list, function (query) {
        verify_string += '|' + query;
    });

    var md5 = crypto.createHash('md5');
    console.log('verify_string:', verify_string);
    md5.update(verify_string);
    return md5.digest('hex');
};

Filter.prototype.after = function (err, msg, session, resp, next) {
    next(err);
};
